<?php
class Api_Vm
{
	/**
	 * 
	 * Tao may ao
	 * @param string $username
	 * @param string $vmname
	 * @param string $tempaltePath
	 * @return true: thanh cong , false : that bai
	 */
	public function  createVm($username,$vmname,$templatePath)
	{
	    $command=SITE_PATH."/library/api/shell/create-vm.sh ".$username." ".$vmname." ".$templatePath;
        exec($command, $output);
        
        if(($output == null))
        	return false;
        
        $countOutput = count($output);
        if($countOutput < 3)
        	return false; 
        
        if((substr($output[1],0,12)=="Transferring") && (substr($output[$countOutput-1], 0,5) == "Done."))
        	return true;
        else 
            return false;
    }
    
    /**
     * 
     * Xoa may ao
     * @param string $username
     * @param string $vmname
     * @return true: thanh cong false: that bai
     */
    public function deleteVm($username,$vmname)
    {
    	$command = SITE_PATH."/library/api/shell/delete-vm.sh ".$username." ".$vmname;
    	exec($command, $output);
    	if($output == null)
    		return true;
    	else 
    		return false;		
    }  
    /**
     * 
     * Khoi dong may ao
     * @param string $username
     * @param string $vmname
     * @param int $cpu
     * @param int $ram
     * @param float $duration
     * @return array info{'default_name','ip','host','create_date'}
     */
    public function startVm($username,$vmname,$cpu,$ram,$duration) 
    {
    	$info = array('default_name'=>'','ip'=>'','host'=>'','create_date'=>'','status'=>2);
		$command=SITE_PATH."/library/api/shell/start-vm.sh ".$username." ".$vmname." ".$cpu." ".$ram." ".$duration;
		exec($command, $output);
        
		if(($output == null) || (count($output) != 4))
			return $info;
		
        if((substr($output[0],0,2)=="vm") && (trim($output[1]) != '')) 
        {
            $info['default_name'] = $output[0];
            $info['ip']           = $output[1];
            $info['host']         = $output[2];
            $info['create_date']  = $output[3];
	    	$info['status']       = 1; //running
        }
         return $info;
    }
    
    /**
     * Dung may ao
     * @param string $default_name
     * @return true : thanh cong , false : that bai
     */
    
    public function stopVm($default_name)
    {
    	$command = SITE_PATH."/library/api/shell/stop-vm.sh ".$default_name;
    	exec($command, $output);
    	
    	if($output == null)
    		return false;
    	
    	if($output[0] =="")
    		return true;
    	else 
    		return false;
    }
}